from flask import Blueprint,request,jsonify
# 密码加密
from werkzeug.security import generate_password_hash,check_password_hash
from conf.comm import sqlalchemy_context
from database import *
import json
import re,random
from utils.comm import send_message
from utils.redisconn import r , RedisCon
import os,uuid
from utils.redisconn import myup

#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()

def reg():
    #获取用户输入
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    # 有效性验证
    ret = re.match("^1[3-9]\d{9}$",data['mobile'])
    if not ret:
        return jsonify({'code':10012,'mes':'手机号有误'})

    #构造user
    try:
         user = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
         db.session.add(user)
         db.session.commit()
         return jsonify({"code":200})
    except:
        return jsonify({"code":10010})


@bp_users.route('/sendsms',methods=['POST'])
def sendsms():
    #传递手机号
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    #有效性验证，正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not reg:
        return jsonify({'code':10012,'mes':'必须输入手机号'})
    #生成验证码    
    code = str(random.randint(100000,999999))
    #调用短信接口
    flag = send_message(mobile,code,1)
    if flag:
        #发送成功，存入redis
        r.set_str(mobile,code,60)
        #返回结果（验证码）
        return jsonify({'code':200,'smscode':code})
    else:
        return jsonify({'code':20011,'mes':'发送失败，请重试'})

from utils.myjwt import myjwt

@bp_users.route('/login/',methods=['POST'])
def login():
     #用户名登录
    username = request.args.get('username')
    password = request.args.get('password')
    mobile = request.args.get('mobile')
    code = request.args.get('code')
    # print(username,password)
    # return 'ok'
    if username:
        #查询这个用户信息 
        user = User.query.filter_by(username=username).first()
        if user:
            if check_password_hash(user.password,password):
                return jsonify({'code':200,'msg':'登录成功','userid':user.id,'username':user.username,'mobile':user.mobile})
            else:
                return jsonify({'code':20030,'msg':'用户名或密码错误'}) 
        else:
            return jsonify({'code':20020,'msg':'该用户不存在'})

    if mobile:    
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form

        mobile = data['mobile']
        code = data['code']

        r = RedisCon()
        hcode = r.get_str(mobile)
        if hcode:
            if int(code) == int(hcode):
                user = User.query.filter_by(mobile=mobile).first()
                if not user:
                    user = User(username=mobile, mobile=mobile)
                    db.session.add(user)
                    db.session.commit()
                # 清除
                r.del_str(mobile)
                token = myjwt.jwt_encode({'data': {'username': user.username, 'userid': user.id}})
                return jsonify({'code': 200, 'userid': user.id, 'username': user.username, 'token': token})
            else:
                return jsonify({'code': 20012, 'mes': '验证码错误'})


# 返回用户信息接口
@bp_users.route('/getuserinfo')
def getuserinfo():
    # 数据库查询返回
        id = request.args.get('userid')
        user = User.query.filter_by(id=id).first()
        dict = {}
        dict['id'] = user.id
        dict['username'] = user.username
        dict['mobile'] = user.mobile
        dict['avater'] = user.avater
        return jsonify({'code':200,'user':dict})
    

# 在执行接口前调用
@bp_users.before_request
def before_request():
    # 定义一个白名单，把不需要token认证的接口放到列表里
    list=['/users/login','/users/reg','/users/sendsms']
    if request.path not in list:
    # 获取token
        try:
            token = request.headers['Token']
            
        except:
            return jsonify({"code": 403, 'mes': '请传递token'})
        # 解密重新对比token
        newtoken = myjwt.jwt_decode(token)
        if newtoken and myjwt.check(token, newtoken):
            pass
        else:
            return jsonify({"code": 403, 'mes': 'token错误'})


# 头像上传
@bp_users.route('/upload',methods=['POST'])
def upload():
    # 获取文件
    file = request.files['file']
    # 上传到upload文件夹
    # 解决文件名被覆盖的问题
    # 1.文件重命名  文件名，后缀
    # 获取文件名
    filetext = os.path.splitext(file.filename)[1]
    newfile = uuid.uuid4().hex + filetext
    # 2.在upload下面建立一个文件夹，专业存，文件夹的名字为userid
    userid = request.form.get('userid')
    # 根据userid创建文件夹
    # 判断此用户文件夹是否存在，存在直接写文件，不存在创建
    path = './static/upload/' + str(userid)
    # 不存在创建文件
    if not os.path.exists(path):
        os.mkdir(path)
    file.save(os.path.join(path,newfile))
    # 更新到数据库
    User.query.filter_by(id=userid).update({'avater':newfile})
    db.session.commit()

    # 上传到又拍云
    myup.pupload(userid,newfile)
    return jsonify({"code":200,'filename':newfile})


from utils.myyunpayun import myupyun
@bp_users.route('/test',methods=['POST'])
def method_name():
    file = request.files['file']
    myupyun.upload(file)


from utils.myfiles import myf
# 获取某用户下的所有文件
@bp_users.route('/getFiles',methods=['GET','DELETE'])
def getFiles():
    if request.method == "GET":
        # 后去用户id
        id = request.args.get('userid')
        # 根据用户id调用文件类获取所有文件
        list = myf.show_all(id)
        filelist=[]
        for i in list:
            dict={}
            dict['name'] = i
            dict['url'] = 'http://localhost:5000/static/upload/'+str(id)+"/"+str(i)
            filelist.append(dict)
        return jsonify({'code':200,'list':filelist})

    elif request.method == "DELETE":
        # 删除
        # 获取userid,文件名
        userid = request.args.get('userid')
        filename = request.args.get('filename')
        # 调用删除文件方法
        myf.remove_file(userid,filename)
        # 返回结果
        return jsonify({'code':200})